/* eslint-disable no-plusplus */
/**
 * @Description: 满减满赠
 * @author ourslookAdmin
 * @date 2019-09-06 15:14:10
 */
import React, { Fragment } from 'react';
import {
  BackTop,
  Button,
  Card,
  Checkbox,
  Col,
  DatePicker,
  Divider,
  Form,
  Icon,
  Input,
  Radio,
  Row,
  Select,
  Spin,
  Switch,
  Table,
  Tooltip,
} from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import numeral from 'numeral';
import Modal from 'drag-modal';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import DefaultImage from '../../../components/ourslook/DefaultImage';
import Ellipsis from '../../../components/ourslook/Ellipsis';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const { MonthPicker, RangePicker } = DatePicker;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class Reward extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    // {title: 'id', dataIndex: 'id', width: 120, align: 'center', sorter: true, key: 'id'},
    {
      title: '活动名称',
      dataIndex: 'name',
      width: 120,
      align: 'center',
      sorter: true,
      key: 'name',
    },
    {
      title: '有效时间',
      dataIndex: 'startTime',
      // width: 250,
      align: 'center',
      sorter: false,
      key: 'start_time',
      render: (value, record, index) => `${value}至${record.endTime}`,
    },
    {
      title: '活动范围',
      dataIndex: 'rangeType',
      width: 120,
      align: 'center',
      sorter: true,
      key: 'range_type',
      render: (value, record, index) => {
        let str = '';
        if (value === 'part') {
          str = '指定商品';
        } else if (value === 'all') {
          str = '全部商品';
        }
        return str;
      },
    },
    // {
    //   title: '付款订单数',
    //   dataIndex: 'voOrderTotalNum',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'vo_order_total_num',
    //   render: (value, record, index) => {
    //     if (!value) {
    //       return '- -';
    //     }
    //     return value;
    //   },
    // },
    // {
    //   title: '付款人数',
    //   dataIndex: 'voOrderTotalUser',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'vo_order_total_user',
    //   render: (value, record, index) => {
    //     if (!value) {
    //       return '- -';
    //     }
    //     return value;
    //   },
    // },
    // {
    //   title: '订单实付金额',
    //   dataIndex: 'voOrderTotalMoney',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'vo_order_total_money',
    //   render: (value, record, index) => {
    //     if (!value) {
    //       return '- -';
    //     }
    //     return value;
    //   },
    // },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'status',
      render: (value, record, index) => (
        <React.Fragment>
          <div>
            <Switch
              checkedChildren="上架"
              unCheckedChildren="下架"
              onChange={val => {
                this.setStateByTableColume(record, index);
                this.updateStatus(val);
              }}
              checked={value === 1}
            />
          </div>
        </React.Fragment>
      ),
    },
    // {
    //   title: '微信二维码',
    //   dataIndex: 'wxQrCode',
    //   width: 100,
    //   align: 'center',
    //   sorter: false,
    //   render: (value, record, index) =>
    //     value === undefined ? (
    //       <Tag style={{cursor: 'default'}} className={styles.label_primary}>
    //         未生成
    //       </Tag>
    //     ) : (
    //       <Tag style={{cursor: 'default'}} className={styles.label_success}>
    //         已生成
    //       </Tag>
    //     ),
    // },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 190,
      align: 'center',
      sorter: true,
      key: 'create_time',
    },
    {
      title: '操作',
      dataIndex: '',
      width: 180,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('promotionsreward:update')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider hidden={!hasPermission('promotionsreward:update')} type="vertical" />
          <a
            hidden={!hasPermission('promotionsreward:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
          <Divider hidden={!hasPermission('promotionsreward:info')} type="vertical" />
          {/*<a*/}
          {/*  hidden={!hasPermission('promotionsreward:update')}*/}
          {/*  onClick={() => {*/}
          {/*    this.createWxImage(record, index);*/}
          {/*  }}*/}
          {/*>*/}
          {/*  <Tooltip*/}
          {/*    title={*/}
          {/*      <FormattedMessage id="ours.curd.list.createWxImage" defaultMessage="生成二维码"/>*/}
          {/*    }*/}
          {/*  >*/}
          {/*    <Icon type="file-image"/>*/}
          {/*  </Tooltip>*/}
          {/*</a>*/}
          {/*<Divider hidden={!hasPermission('promotionsreward:update')} type="vertical"/>*/}
          <a
            hidden={!hasPermission('promotionsreward:save')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.copy();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.copy" defaultMessage="复制" />}>
              <Icon type="copy" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: Reward.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'name',
      label: '活动名称',
      placeholder: '活动名称',
    },
    {
      type: 'DATE_RANGE',
      field: 'startTime',
      label: '生效时间',
      placeholder: ['生效时间', ''],
    },
    {
      type: 'SELECT',
      field: 'rangeType',
      label: '请选择活动范围',
      placeholder: '活动商品范围类型',
      list: [
        { id: '', name: '请选择活动范围' },
        { id: 'all', name: '全部可用' },
        { id: 'part', name: '部分商品可用' },
      ],
    },

    {
      type: 'INPUT',
      field: 'status',
      label: '状态',
      placeholder: '状态',
    },
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {
        circleType: 0,
      },
      showList: 2,
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}promotionsreward/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const promotionsReward = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url =
          promotionsReward.id == null ? '/promotionsreward/save' : '/promotionsreward/update';
        //对象删除一个属性
        //delete promotionsReward.xxxxPros;
        promotionsReward.startTime =
          promotionsReward.timeBetween !== undefined
            ? `${promotionsReward.timeBetween[0].format('YYYY-MM-DD HH:mm:ss')}`
            : null;
        promotionsReward.endTime =
          promotionsReward.timeBetween !== undefined
            ? `${promotionsReward.timeBetween[1].format('YYYY-MM-DD HH:mm:ss')}`
            : null;
        if (promotionsReward.rangeType === 'all') {
          promotionsReward.partMailProductList = [];
        } else {
          promotionsReward.partMailProductList = this.editForm.state.partMailProductList;
        }
        const preferentialList = this.editForm.state.preferentialList;
        for (let i = 0; i < preferentialList.length; i++) {
          if (preferentialList[i].delete) {
            preferentialList.splice(i, 1);
          }
        }
        //处理circleType
        if (promotionsReward.preferential.circleType === 0) {
          promotionsReward.circleType = false;
        } else if (promotionsReward.preferential.circleType === 1) {
          promotionsReward.circleType = true;
        }

        if (
          preferentialList === undefined ||
          preferentialList == null ||
          preferentialList.length === 0
        ) {
          uiUtils.showMessage('至少有一个优惠！', 'warning');
          return;
        }
        //校验优惠内容
        let flag = false;
        for (let i = 0; i < preferentialList.length; i++) {
          // eslint-disable-next-line operator-assignment
          preferentialList[i].discount = preferentialList[i].discount * 10;
          if (
            preferentialList[i].existGift ||
            preferentialList[i].existCoupon ||
            preferentialList[i].isOrderOffer ||
            preferentialList[i].isGiftScore ||
            preferentialList[i].postage
          ) {
            //五种优惠有其一即可
            flag = true;
          }
          if (preferentialList[i].isOrderOffer) {
            if (
              (preferentialList[i].discount === 0 || preferentialList[i].discount === undefined) &&
              (preferentialList[i].cash === 0 ||
                preferentialList[i].cash === '0.00' ||
                preferentialList[i].cash === undefined ||
                preferentialList[i].cash === '')
            ) {
              uiUtils.showMessage('选择订单优惠，则折扣和满减至少有一个有效！', 'warning');
              return;
            }
          }
        }
        if (!flag) {
          uiUtils.showMessage('至少有一个优惠！', 'warning');
          return;
        }

        promotionsReward.preferentialVos = preferentialList;
        delete promotionsReward.preferential;
        delete promotionsReward.timeBetween;

        console.log('promotionsReward:', promotionsReward);

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: promotionsReward,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!promotionsReward.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = (id, type) => {
    this.setState({
      editModelConfirmLoading: true,
    });
    requestPromise(`${getWebPath(`/promotionsreward/info/${id}`)}`, {
      method: 'GET',
    }).then(res => {
      this.setState({
        editModelConfirmLoading: false,
      });
      const promotionsReward = res.promotionsReward;
      if (type === 'copy') {
        // promotionsReward.id = undefined;
      }

      if (promotionsReward.preferentialVos !== undefined) {
        for (let i = 0; i < promotionsReward.preferentialVos.length; i++) {
          const obj = promotionsReward.preferentialVos[i];
          //减免，打折
          promotionsReward.preferentialVos[i].isOrderOffer = false;
          if (
            obj.cash !== 0 &&
            obj.cash !== '0.00' &&
            obj.cash !== undefined &&
            (obj.discount === undefined || obj.discount === 0)
          ) {
            promotionsReward.preferentialVos[i].isOrderOffer = true;
            promotionsReward.preferentialVos[i].orderOfferType = 2;
          } else if (obj.discount !== 0 && obj.discount !== undefined) {
            promotionsReward.preferentialVos[i].orderOfferType = 1;
            promotionsReward.preferentialVos[i].isOrderOffer = true;

            // if (type === 'copy') {
            promotionsReward.preferentialVos[i].discount = obj.discount / 10;
            // }
          }
          //积分
          if (obj.score !== undefined && obj.score !== 0) {
            promotionsReward.preferentialVos[i].isGiftScore = true;
          } else {
            promotionsReward.preferentialVos[i].isGiftScore = false;
          }
          //优惠券
          promotionsReward.preferentialVos[i].existCoupon = false;
          if (obj.preferentialObjsCoupon !== undefined && obj.preferentialObjsCoupon.length !== 0) {
            promotionsReward.preferentialVos[i].existCoupon = true;
          }
          //赠品
          promotionsReward.preferentialVos[i].existGift = false;
          if (obj.preferentialObjsGift !== undefined && obj.preferentialObjsGift.length !== 0) {
            promotionsReward.preferentialVos[i].existGift = true;
          }
        }
      }
      this.editForm.setState({
        preferentialList: promotionsReward.preferentialVos || [],
        partMailProductList: promotionsReward.partMailProductList,
      });
    });
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  operateByIds = status => {};

  //========其他所有的处理方法，请在按照约定进行处理==========

  copy = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    selectedRows[0].name = `${selectedRows[0].name}_copy`;
    const id = selectedRows[0].id;
    selectedRows[0].id = undefined;

    this.setState({
      editModalType: 'copy',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="复制" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(id, 'copy');
  };

  /**
   * 导出数据
   * @param isExcel
   */
  exportsAllToExcel = isExcel => {
    // eslint-disable-next-line
    let params = JSON.parse(JSON.stringify(this.params));
    //删除分页属性，导出 当前查询条件内的所有数据。
    delete params.page;
    delete params.limit;

    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }
  };

  updateStatus = val => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    let status;
    if (val) {
      status = 1;
    } else {
      status = -1;
    }
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    this.setState({
      loading: true,
    });
    //const data = 'modelIds=' + ids.join(',') + '&status=' + status;
    const data = {
      modelIds: ids.join(','),
      status,
    };
    requestPromise(`${getWebPath()}promotionsreward/operatePromotionsRewardByIds`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: data,
    }).then(res => {
      this.setState({
        loading: false,
      });
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );
        this.requestList();
      }
    });
  };

  createWxImage = (record, index) => {
    //此处如果它的类型值为空， 为了不让下面的接口出现异常，这里传入-1， -1 在接口中也代表该值不存在
    // if (record.wxQrCode) {
    //   uiUtils.showConfirm(formatMessage({ id: '已经存在二维码，是否再次生成？' }), () => {
    //     requestPromise(
    //       `${getWebPath(
    //         `/promotionsreward/createWxImage?id=${record.id}&resType=${record.resType}`
    //       )}`,
    //       {
    //         method: 'GET',
    //       }
    //     ).then(res => {
    //       if (res && res.code === 0) {
    //         uiUtils.showMessage('操作成功');
    //         this.requestList();
    //       }
    //     });
    //   });
    // } else {
    //   uiUtils.showConfirm(formatMessage({ id: '是否生成二维码？' }), () => {
    //     requestPromise(
    //       `${getWebPath(
    //         `/promotionsreward/createWxImage?id=${record.id}&resType=${record.resType}`
    //       )}`,
    //       {
    //         method: 'GET',
    //       }
    //     ).then(res => {
    //       if (res && res.code === 0) {
    //         uiUtils.showMessage('操作成功');
    //         this.requestList();
    //       }
    //     });
    //   });
    // }
  };

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}promotionsreward/list`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const firstBtnStyle = {
      style: {
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };
    const btnStyle = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };
    const exstyle = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('promotionsreward:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            {/*<Button
              type="primary"
              icon="edit"
              {...btnStyle}
              onClick={this.update}
              hidden={!hasPermission('promotionsreward:update')}
            >
              <FormattedMessage id="ours.curd.list.update" defaultMessage="修改"/>
            </Button>
            <Button
              type="primary"
              icon="info-circle"
              {...btnStyle}
              onClick={this.view}
              hidden={!hasPermission('promotionsreward:info')}
            >
              <FormattedMessage id="ours.curd.list.info" defaultMessage="查看"/>
            </Button>*/}
            <Button
              type="danger"
              icon="delete"
              {...btnStyle}
              onClick={this.del}
              hidden={!hasPermission('promotionsreward:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1200 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Reward;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
  };

  params = {
    page: 1,
    limit: 10,
  };

  requestCouponParams = {
    page: 1,
    limit: 10,
  };

  requestGiftParams = {
    page: 1,
    limit: 10,
  };

  constructor(props) {
    super(props);
    // noinspection JSDuplicatedDeclaration
    this.state = {
      rewardType: 1 /*默认是满X元*/,
      preferentialList: this.getDefaultPreferentialList(),
      partMailProductList: [],
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    // if (nextProps.model) {
    // this.state = {};
    // //使用setFieldsValue实现修改form value的值，不用使用 this.setState({});
    // this.props.model.xxx = 'value';
    // this.props.form.setFieldsValue({xxx: 'value'});
    // }
  }

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  getDefaultPreferentialList = () => {
    const defualtPreferentialList = [];
    if (this.props.type === 'add') {
      defualtPreferentialList.push({
        meet: '',
        cash: 0,
        discount: '',
        postage: false,
        score: 0,
        isGiftScore: false,
        isOrderOffer: false,
        existCoupon: false,
        existGift: false,
        preferentialObjsGift: [],
        preferentialObjsCoupon: [],
      });
    }
    return defualtPreferentialList;
  };

  addRow = () => {
    const { preferentialList: newPreferentialList } = this.state;
    newPreferentialList.push({
      meet: '',
      cash: 0,
      discount: '',
      postage: false,
      score: 0,
      isGiftScore: false,
      isOrderOffer: false,
      existCoupon: false,
      existGift: false,
      preferentialObjsGift: [],
      preferentialObjsCoupon: [],
    });
    this.setState({
      preferentialList: newPreferentialList,
    });
  };

  delRow = index => {
    const { preferentialList: newPreferentialList } = this.state;
    if (index !== undefined && index !== 0) {
      // newPreferentialList.splice(index, 1);
      newPreferentialList[index].delete = true;
      this.setState({
        preferentialList: newPreferentialList,
      });
    }
  };

  /**
   *拉取商品
   * */
  requestList = () => {
    this.params.productName = this.state.likeProductName;
    this.params.status = 2;
    const partMailProductList = this.state.partMailProductList;
    if (partMailProductList) {
      this.params.notInProductIds = partMailProductList.map(value => value.id).join(',');
      this.params.notInRewardProduct = '1';
    }
    requestLists(this, `${getWebPath()}mailproduct/listByNotInProductIds`, this.params);
  };

  /*打开选择商品窗口*/
  openSelectProduct = () => {
    this.setState({
      isShowSelectProduct: true,
    });

    this.params.page = 1;
    this.state.likeProductName = null;
    this.requestList();
  };

  okSelectProduct = () => {
    const { selectedRows, selectedIds } = this.state;
    console.log(selectedRows, selectedIds);
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    const { partMailProductList: newPartMailProductList } = this.state;

    //合并数据
    // eslint-disable-next-line guard-for-in,no-restricted-syntax,no-plusplus
    for (let i = 0; i < selectedRows.length; i++) {
      newPartMailProductList.push(selectedRows[i]);
    }
    this.setState({
      partMailProductList: newPartMailProductList,
      isShowSelectProduct: false,
    });
  };

  deleteSelectProduct = (record, index) => {
    const { partMailProductList: newPartMailProductList } = this.state;
    // eslint-disable-next-line no-plusplus
    //从下标为i开始,删除1个元素。
    newPartMailProductList.splice(index, 1);
    this.setState({ partMailProductList: newPartMailProductList });
  };

  /*优惠券*/
  /**
   * @param index 索引
   */
  openSelectCoupon = index => {
    this.setState({
      isShowSelectCoupon: true,
      currentItemIndex: index,
    });

    this.requestCouponParams.page = 1;
    this.state.likeCouponName = null;
    this.requestCouponList(index);
  };

  okSelectCoupon = () => {
    const {
      selectedRows,
      selectedIds,
      selectedIndexs,
      currentItemIndex,
      preferentialList,
    } = this.state;
    console.log(selectedRows, selectedIds);
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (currentItemIndex === undefined || currentItemIndex === null) {
      return;
    }

    const preferentialObjsCoupon = preferentialList[currentItemIndex].preferentialObjsCoupon || [];

    for (let i = 0; i < selectedRows.length; i++) {
      const objNum = this.props.form.getFieldsValue([`objNum-${selectedIndexs[i]}`])[
        `objNum-${selectedIndexs[i]}`
      ];
      selectedRows[i].objNum = objNum;
      const id = selectedRows[i].id;
      selectedRows[i].objId = id;
      selectedRows[i].id = undefined;
      preferentialObjsCoupon.push(selectedRows[i]);
    }
    preferentialList[currentItemIndex].preferentialObjsCoupon = preferentialObjsCoupon;
    this.setState({
      preferentialList,
      isShowSelectCoupon: false,
    });
  };

  deleteSelectCounpon = (record, index, itemIndex) => {
    console.log('itemIndex', itemIndex);
    if (itemIndex === undefined || itemIndex === null) {
      return;
    }
    const { currentItemIndex, preferentialList } = this.state;
    preferentialList[currentItemIndex].preferentialObjsCoupon.splice(index, 1);
    this.setState({
      preferentialList,
    });
  };

  requestCouponList = currentItemIndex => {
    this.requestCouponParams.title = this.state.likeCouponName;
    this.requestCouponParams.status = 1;
    //过滤存在的
    const { preferentialList } = this.state;
    if (currentItemIndex === undefined) {
      // eslint-disable-next-line no-param-reassign
      currentItemIndex = this.state.currentItemIndex;
    }
    if (preferentialList[currentItemIndex].preferentialObjsCoupon !== undefined) {
      this.requestCouponParams.notInCouponIds = preferentialList[
        currentItemIndex
      ].preferentialObjsCoupon
        .map(value => value.objId)
        .join(',');
    }

    requestPromise(`${getWebPath()}mailcoupon/listNoPerm`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: this.requestCouponParams,
    }).then(res => {
      this.setState({ loading: false });
      if (res && res.code === 0) {
        if (res && res.page) {
          const list = res.page.list.map((item, index) => {
            item.key = index;
            return item;
          });
          this.setState({
            couponList: list,
            selectedIndexs: [],
            selectedRows: [],
            selectedIds: [],
            pagination: uiUtils.pagination(res, (current, limit) => {
              this.requestCouponParams.page = current;
              if (typeof limit !== 'undefined') {
                this.requestCouponParams.limit = limit;
              }
              this.requestCouponList();
            }),
          });
        }
      }
    });
  };

  /*赠品*/
  openSelectGift = index => {
    this.setState({
      isShowSelectGift: true,
      currentItemIndex: index,
    });

    this.requestGiftParams.page = 1;
    this.state.likeGiftName = null;
    this.requestGiftList(index);
  };

  okSelectGift = () => {
    const {
      selectedRows,
      selectedIds,
      selectedIndexs,
      currentItemIndex,
      preferentialList,
    } = this.state;
    console.log(selectedRows, selectedIds);
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    const preferentialObjsGift = preferentialList[currentItemIndex].preferentialObjsGift || [];

    for (let i = 0; i < selectedRows.length; i++) {
      const objNum = this.props.form.getFieldsValue([`objNum-${selectedIndexs[i]}`])[
        `objNum-${selectedIndexs[i]}`
      ];
      selectedRows[i].objNum = objNum;
      const id = selectedRows[i].id;
      selectedRows[i].objId = id;
      selectedRows[i].id = undefined;
      preferentialObjsGift.push(selectedRows[i]);
    }
    preferentialList[currentItemIndex].preferentialObjsGift = preferentialObjsGift;
    this.setState({
      preferentialList,
      isShowSelectGift: false,
    });
  };

  deleteSelectGift = (record, index, itemIndex) => {
    if (itemIndex === undefined || itemIndex === null) {
      return;
    }

    const { currentItemIndex, preferentialList } = this.state;
    preferentialList[currentItemIndex].preferentialObjsGift.splice(index, 1);
    this.setState({
      preferentialList,
    });
  };

  requestGiftList = currentItemIndex => {
    this.requestGiftParams.title = this.state.likeGiftName;
    this.requestGiftParams.status = 1;
    //过滤存在的
    const { preferentialList } = this.state;
    if (currentItemIndex === undefined) {
      // eslint-disable-next-line no-param-reassign
      currentItemIndex = this.state.currentItemIndex;
    }
    if (preferentialList[currentItemIndex].preferentialObjsGift !== undefined) {
      this.requestGiftParams.notInGiftIds = preferentialList[currentItemIndex].preferentialObjsGift
        .map(value => value.objId)
        .join(',');
    }

    requestPromise(`${getWebPath()}promotiongift/listNotPerm`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: this.requestGiftParams,
    }).then(res => {
      this.setState({ loading: false });
      if (res && res.code === 0) {
        if (res && res.page) {
          const list = res.page.list.map((item, index) => {
            item.key = index;
            return item;
          });
          this.setState({
            giftList: list,
            selectedIndexs: [],
            selectedRows: [],
            selectedIds: [],
            pagination: uiUtils.pagination(res, (current, limit) => {
              this.requestGiftParams.page = current;
              if (typeof limit !== 'undefined') {
                this.requestGiftParams.limit = limit;
              }
              this.requestGiftList();
            }),
          });
        }
      }
    });
  };

  getCouponColumns = itemIndex => {
    //展示-优惠券
    const preferentialObjsCouponShowColumns = [
      /*{
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 90,
      },*/
      {
        title: '优惠券名称',
        dataIndex: 'title',
        width: 220,
        key: 'title',
        render: value => (
          <Ellipsis length={60} tooltip>
            {value}
          </Ellipsis>
        ),
      },
      {
        title: '优惠券类型',
        // width: 120,
        align: 'center',
        key: 'appoint_type',
        render: (value, record, index) => {
          let appointTypeName = '';
          if (value.appointType === 1) {
            appointTypeName = `满减券`;
          } else if (value.appointType === 2) {
            appointTypeName = `折扣券`;
          } else {
            appointTypeName = `随机金额券`;
          }
          return appointTypeName;
        },
      },
      {
        title: '面额',
        align: 'right',
        key: 'denominations',
        // width: 120,
        render: (value, record, index) => {
          let formatCondition = '-';
          if (value.denominations !== null && value.denominations !== undefined) {
            if (record.appointType !== 2) {
              formatCondition = `￥${numeral(value.denominations).format('0,0.00')}`;
            } else {
              formatCondition = `${value.denominations}折`;
            }
          }
          return formatCondition;
        },
      },
      {
        title: '剩余库存',
        key: 'stockQty',
        render: (value, record, index) => {
          if (record.stockQty !== undefined) {
            if (record.totalTake !== undefined) {
              return record.stockQty - record.totalTake;
            }
          }
          return '---';
        },
      },
      {
        title: '赠券数量',
        key: 'objNum',
        render: (value, record, index) =>
          // console.log(value, record);
          record.objNum,
      },
      {
        title: '操作',
        key: '',
        dataIndex: '',
        width: 120,
        fixed: 'right',
        render: (value, record, index) => (
          <React.Fragment>
            <a
              hidden={this.props.type === 'view'}
              onClick={() => {
                this.deleteSelectCounpon(record, index, itemIndex);
              }}
            >
              <Tooltip
                title={<FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />}
              >
                <Icon type="delete" />
              </Tooltip>
            </a>
          </React.Fragment>
        ),
      },
    ];
    return preferentialObjsCouponShowColumns;
  };

  getGiftColumns = itemIndex => {
    const preferentialObjsGiftShowColumns = [
      /*  {
          title: "id",
          key: "id",
          width: 90,
          render:(val)=> val.id
        },*/
      {
        title: '名称',
        key: 'giftName',
        width: 200,
        render: value => (
          <Ellipsis length={60} tooltip>
            {value.giftName}
          </Ellipsis>
        ),
      },
      {
        title: '赠送数量',
        key: 'objNum',
        render: val => val.objNum,
      },
      {
        title: '操作',
        key: '',
        dataIndex: '',
        width: 120,
        fixed: 'right',
        render: (value, record, index) => (
          <React.Fragment>
            <a
              hidden={this.props.type === 'view'}
              onClick={() => {
                this.deleteSelectGift(record, index, itemIndex);
              }}
            >
              <Tooltip
                title={<FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />}
              >
                <Icon type="delete" />
              </Tooltip>
            </a>
          </React.Fragment>
        ),
      },
    ];
    return preferentialObjsGiftShowColumns;
  };

  getCircleType = model => (model.circleType === undefined ? 1 : model.circleType ? 1 : 0);

  getViewIndex = index => {
    let viewIndex = 0;
    this.state.preferentialList.forEach((value, index1) => {
      if (index1 <= index) {
        if (value.delete === null || value.delete === undefined) {
          viewIndex += 1;
        }
      }
    });
    return viewIndex;
  };

  // todo 微信二维码

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };

    //列表展示-商品
    const partMailProductColumns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 90,
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
        width: 220,
        key: 'productName',
        render: value => (
          <Ellipsis length={60} tooltip>
            {value}
          </Ellipsis>
        ),
      },
      {
        title: '封面',
        dataIndex: 'imageCover',
        key: 'imageCover',
        render: value => <DefaultImage src={value} width="100" />,
      },
      {
        title: '操作',
        key: '',
        dataIndex: '',
        width: 120,
        fixed: 'right',
        render: (value, record, index) => (
          <React.Fragment>
            <a
              hidden={this.props.type === 'view'}
              onClick={() => {
                this.deleteSelectProduct(record, index);
              }}
            >
              <Tooltip
                title={<FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />}
              >
                <Icon type="delete" />
              </Tooltip>
            </a>
          </React.Fragment>
        ),
      },
    ];
    //选择框-商品
    const selectProductColumns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 90,
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
        width: 220,
        key: 'productName',
        render: value => (
          <Ellipsis length={60} tooltip>
            {value}
          </Ellipsis>
        ),
      },
      {
        title: '封面',
        dataIndex: 'imageCover',
        key: 'imageCover',
        render: value => <DefaultImage src={value} width="100" />,
      },
    ];

    //选择框-优惠券
    const preferentialObjsCouponColumns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 90,
      },
      {
        title: '优惠券名称',
        dataIndex: 'title',
        width: 220,
        key: 'title',
        render: value => (
          <Ellipsis length={60} tooltip>
            {value}
          </Ellipsis>
        ),
      },
      {
        title: '优惠券类型',
        // width: 120,
        align: 'center',
        key: 'appoint_type',
        render: (value, record, index) => {
          let appointTypeName = '';
          if (value.appointType === 1) {
            appointTypeName = `满减券`;
          } else if (value.appointType === 2) {
            appointTypeName = `折扣券`;
          } else {
            appointTypeName = `随机金额券`;
          }
          return appointTypeName;
        },
      },
      {
        title: '面额',
        align: 'right',
        key: 'denominations',
        // width: 120,
        render: (value, record, index) => {
          let formatCondition = '-';
          if (value.denominations !== null && value.denominations !== undefined) {
            if (record.appointType !== 2) {
              formatCondition = `￥${numeral(value.denominations).format('0,0.00')}`;
            } else {
              formatCondition = `${value.denominations}折`;
            }
          }
          return formatCondition;
        },
      },
      {
        title: '剩余库存',
        key: 'stockQty',
        render: (value, record, index) => {
          if (record.stockQty !== undefined) {
            if (record.totalTake !== undefined) {
              return record.stockQty - record.totalTake;
            }
          }
          return '---';
        },
      },
      {
        title: '赠券数量',
        key: 'objNum',
        render: (value, record, index) => (
          <Form>
            <FormItem style={{ margin: 0 }}>
              {getFieldDecorator(`objNum-${index}`, {
                rules: [
                  {
                    required: true,
                    message: '请输入数量',
                  },
                  rulesReg('plus'),
                ],
                initialValue: 1,
              })(<Input style={{ width: '50px' }} />)}
            </FormItem>
          </Form>
        ),
      },
    ];

    //选择-赠品
    const preferentialObjsGiftColumns = [
      {
        title: 'id',
        key: 'id',
        width: 90,
        render: val => val.id,
      },
      {
        title: '名称',
        key: 'giftName',
        width: 200,
        render: value => (
          <Ellipsis length={60} tooltip>
            {value.giftName}
          </Ellipsis>
        ),
      },
      {
        title: '赠送数量',
        key: 'objNum',
        render: (value, record, index) => (
          <Form>
            <FormItem style={{ margin: 0 }}>
              {getFieldDecorator(`objNum-${index}`, {
                rules: [
                  {
                    required: true,
                    message: '请输入数量',
                  },
                  rulesReg('plus'),
                ],
                initialValue: 1,
              })(<Input style={{ width: '50px' }} />)}
            </FormItem>
          </Form>
        ),
      },
    ];

    console.log('this.state:', this.state);
    console.log('model:', model);
    console.log('field:', this.props.form.getFieldsValue());

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Card
          bordered
          size="small"
          bodyStyle={{ paddingBottom: 10 }}
          style={{ marginBottom: 20 }}
          title="活动基本信息"
        >
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="活动名称" {...formItemLayout}>
                {type === 'view'
                  ? model.name
                  : getFieldDecorator('name', {
                      initialValue: model.name,
                      rules: [
                        {
                          required: true,
                          message: '活动名称必填',
                        },
                        {
                          max: 18,
                          message: '最长18个字符',
                        },
                      ],
                    })(
                      <Input type="text" autocomplete="off" maxlength={18} placeholder="活动名称" />
                    )}
              </FormItem>
            </Col>

            <Col {...colSpanLayout}>
              <FormItem label="生效时间" {...formItemLayout}>
                {type === 'view'
                  ? `${model.startTime}~${model.endTime}`
                  : getFieldDecorator('timeBetween', {
                      initialValue: [
                        model.startTime === undefined || model.startTime === ''
                          ? ''
                          : moment(model.startTime, 'YYYY-MM-DD HH:mm:ss'),
                        model.endTime === undefined || model.endTime === ''
                          ? ''
                          : moment(model.endTime, 'YYYY-MM-DD HH:mm:ss'),
                      ],
                      rules: [
                        {
                          required: true,
                          message: '生效时间必选',
                        },
                      ],
                    })(
                      <RangePicker
                        style={{ width: 330 }}
                        disabledDate={current =>
                          current &&
                          current <
                            moment()
                              .endOf('day')
                              .subtract(1, 'days')
                        }
                        showTime
                        placeholder={['请选择生效开始时间', '请选择生效结束时间']}
                      />
                    )}
              </FormItem>
            </Col>

            <Col {...colSpanLayout}>
              <FormItem label="标签" {...formItemLayout}>
                {type === 'view'
                  ? model.tagId
                  : getFieldDecorator('tagId', {
                      initialValue: model.tagId !== undefined ? `${model.tagId}` : model.tagId,
                      rules: [
                        {
                          max: 18,
                          message: '最长18个字符',
                        },
                      ],
                    })(<Input type="text" autocomplete="off" placeholder="标签" />)}
              </FormItem>
            </Col>

            {type === 'view' && (
              <Col {...colSpanLayout}>
                <FormItem label="微信二维码" {...formItemLayout}>
                  <DefaultImage src={model.wxQrCode} alt="" width="100px" height="70px" />
                </FormItem>
              </Col>
            )}
          </Row>
          {/*活动范围*/}
          <Row>
            <Col {...colSpanLayout}>
              <FormItem
                label="活动范围"
                {...formItemLayout}
                extra={
                  model.rangeType === 'part' && (
                    <div>
                      {type !== 'view' && (
                        <a
                          onClick={() => {
                            this.openSelectProduct();
                          }}
                        >
                          选择商品
                        </a>
                      )}
                      {this.state.partMailProductList !== undefined &&
                        this.state.partMailProductList.length > 0 && (
                          <Table
                            rowKey="id"
                            style={{ minWidth: '450px' }}
                            columns={partMailProductColumns}
                            dataSource={this.state.partMailProductList}
                          />
                        )}
                    </div>
                  )
                }
              >
                {type === 'view'
                  ? model.rangeType === 'all'
                    ? '全部商品'
                    : '部分商品'
                  : getFieldDecorator('rangeType', {
                      initialValue: model.rangeType === undefined ? 'all' : model.rangeType,
                      rules: [
                        {
                          required: true,
                          message: '活动商品范围必填',
                        },
                      ],
                    })(
                      <Radio.Group
                        onChange={e => {
                          model.rangeType = e.target.value;
                          if (
                            e.target.value === 'part' &&
                            this.state.partMailProductList === undefined
                          ) {
                            this.setState({
                              partMailProductList: [],
                            });
                          }
                        }}
                      >
                        <Radio value="all">全部</Radio>
                        <Radio value="part">指定商品</Radio>
                      </Radio.Group>
                    )}
              </FormItem>
            </Col>
          </Row>
        </Card>

        {/*具体优惠设置*/}
        <Card
          bordered
          size="small"
          bodyStyle={{ paddingBottom: 10 }}
          style={{ marginBottom: 20 }}
          title="优惠信息"
        >
          {/*活动类型*/}
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="活动类型" {...formItemLayout}>
                {type === 'view'
                  ? model.rewardType === 1
                    ? '满X元优惠'
                    : '满N件优惠'
                  : getFieldDecorator('rewardType', {
                      initialValue: model.rewardType === undefined ? 1 : model.rewardType,
                      rules: [],
                    })(
                      <Radio.Group
                        onChange={e => {
                          this.setState({ rewardType: e.target.value });
                        }}
                      >
                        <Radio value={1}>满X元</Radio>
                        <Radio value={2}>满N件</Radio>
                      </Radio.Group>
                    )}
              </FormItem>
            </Col>
          </Row>
          {/*优惠设置*/}
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="优惠设置" {...formItemLayout}>
                {type === 'view'
                  ? model.circleType
                    ? '循环满减'
                    : '阶梯满减'
                  : getFieldDecorator('preferential.circleType', {
                      initialValue: this.getCircleType(model),
                      rules: [],
                    })(
                      <Radio.Group
                        disabled={type === 'update'}
                        onChange={e => {
                          model.circleType = e.target.value;
                          //清除数据
                          const newPreferentialList = [
                            {
                              meet: '',
                              cash: '',
                              discount: '',
                              postage: '',
                              score: '',
                            },
                          ];
                          this.setState({
                            preferentialList: newPreferentialList,
                          });
                        }}
                      >
                        <Radio value={0}>阶梯满减</Radio>
                        <Radio value={1}>循环满减</Radio>
                      </Radio.Group>
                    )}
              </FormItem>
            </Col>
          </Row>
          {this.state.preferentialList.map(
            (item, index) =>
              item.delete === null ||
              (item.delete === undefined && (
                <Form>
                  {this.getCircleType(model) === 0 && (
                    <div
                      style={{
                        marginLeft: '20px',
                        width: '560px',
                        color: '#333',
                        lineHeight: '30px',
                        fontSize: '15px',
                        padding: '1px 10px',
                        backgroundColor: '#f7f8fa',
                        marginBottom: '10px',
                      }}
                    >
                      <span style={{ display: 'inline' }}>{this.getViewIndex(index)}级优惠</span>
                      <a
                        onClick={() => {
                          this.delRow(index);
                        }}
                        hidden={index === 0 || type === 'view'}
                        style={{ float: 'right' }}
                      >
                        删除
                      </a>
                    </div>
                  )}
                  <Row gutter={{ ...rowGutterPxLayout }}>
                    {/*优惠门槛*/}
                    {this.state.rewardType === 1 && (
                      <Col {...colSpanLayout}>
                        <FormItem label="优惠门槛" {...formItemLayout}>
                          满
                          {type === 'view'
                            ? item.meet
                            : getFieldDecorator(`preferential.meet-${index}`, {
                                initialValue: item.meet,
                                rules: [
                                  {
                                    required: true,
                                    message: '必填',
                                  },
                                  rulesReg('money_0_999999'),
                                ],
                              })(
                                <Input
                                  style={{ width: 150, marginLeft: 5, marginRight: 5 }}
                                  type="text"
                                  autocomplete="off"
                                  placeholder="门槛"
                                  onChange={event => {
                                    item.meet = event.target.value;
                                  }}
                                />
                              )}
                          元
                        </FormItem>
                      </Col>
                    )}
                    {this.state.rewardType === 2 && (
                      <Col {...colSpanLayout}>
                        <FormItem label="优惠门槛" {...formItemLayout}>
                          满
                          {type === 'view'
                            ? item.meet
                            : getFieldDecorator(`preferential.meet-${index}`, {
                                initialValue: item.meet === 0 ? undefined : item.meet,
                                rules: [
                                  {
                                    required: true,
                                    message: '必填',
                                  },
                                  rulesReg('plus'),
                                ],
                              })(
                                <Input
                                  style={{ width: 150, marginLeft: 5, marginRight: 5 }}
                                  type="text"
                                  autocomplete="off"
                                  placeholder="门槛"
                                  onChange={event => {
                                    item.meet = event.target.value;
                                  }}
                                />
                              )}
                          件
                        </FormItem>
                      </Col>
                    )}
                  </Row>
                  <Row gutter={{ ...rowGutterPxLayout }}>
                    <span style={{ marginLeft: 59 }}>优惠内容:</span>

                    {getFieldDecorator(`preferential.isOrderOffer-${index}`, {
                      initialValue: item.isOrderOffer,
                    })(
                      <Checkbox
                        checked={item.isOrderOffer}
                        disabled={type === 'view'}
                        style={{ marginLeft: 10 }}
                        onChange={e => {
                          item.isOrderOffer = e.target.checked;
                          if (model.circleType === 1) {
                            item.orderOfferType = 2;
                          } else {
                            item.orderOfferType = 1;
                          }
                          //清空订单金额优惠
                          item.cash = 0;
                          item.discount = 0;
                        }}
                      >
                        订单金额优惠
                      </Checkbox>
                    )}
                    <Fragment>
                      {item.isOrderOffer &&
                        getFieldDecorator(`preferential.orderOfferType-${index}`, {
                          initialValue: item.orderOfferType,
                        })(
                          <Radio.Group
                            style={{
                              display: 'block',
                              marginTop: 20,
                              marginLeft: 180,
                              marginBottom: -30,
                            }}
                            disabled={!item.isOrderOffer || type === 'view'}
                            onChange={e => {
                              item.orderOfferType = e.target.value;
                              item.discount = '';
                              item.cash = '';
                              this.props.form.setFieldsValue({
                                preferential: {
                                  [`discount-${index}`]: undefined,
                                  [`cash-${index}`]: undefined,
                                },
                              });
                            }}
                          >
                            <Radio
                              style={{ display: 'block' }}
                              value={1}
                              disabled={model.circleType === 1}
                            >
                              <FormItem
                                style={{ display: 'inline-block', marginTop: -9 }}
                                {...formItemLayout}
                              >
                                打
                                {type === 'view'
                                  ? item.discount
                                  : getFieldDecorator(`preferential.discount-${index}`, {
                                      initialValue: item.discount === 0 ? undefined : item.discount,
                                      rules: [rulesReg('plusnums5')],
                                    })(
                                      <Input
                                        style={{ width: 150, marginLeft: 5, marginRight: 5 }}
                                        disabled={item.orderOfferType !== 1}
                                        type="text"
                                        autocomplete="off"
                                        placeholder="折扣"
                                        onChange={event => {
                                          item.discount = event.target.value;
                                        }}
                                      />
                                    )}
                                折
                              </FormItem>
                            </Radio>
                            <Radio style={{ display: 'block' }} value={2}>
                              <FormItem
                                style={{ display: 'inline-block', marginTop: -9 }}
                                {...formItemLayout}
                              >
                                减
                                {type === 'view'
                                  ? item.cash
                                  : getFieldDecorator(`preferential.cash-${index}`, {
                                      initialValue: item.cash,
                                      rules: [rulesReg('money_0_999999')],
                                    })(
                                      <Input
                                        disabled={item.orderOfferType !== 2}
                                        style={{ width: 150, marginLeft: 5, marginRight: 5 }}
                                        type="text"
                                        autocomplete="off"
                                        placeholder="元"
                                        onChange={event => {
                                          item.cash = event.target.value;
                                        }}
                                      />
                                    )}
                                元
                              </FormItem>
                            </Radio>
                          </Radio.Group>
                        )}
                    </Fragment>
                  </Row>
                  {/*2，包邮*/}
                  <Row gutter={{ ...rowGutterPxLayout }}>
                    <Col {...colSpanLayout}>
                      {getFieldDecorator(`preferential.postage-${index}`, {
                        initialValue: !item.postage,
                        rules: [],
                      })(
                        <Checkbox
                          disabled={type === 'view'}
                          defaultChecked={item.postage}
                          style={{ marginLeft: 115, marginTop: 20 }}
                          onChange={e => {
                            item.postage = e.target.checked;
                          }}
                        >
                          包邮
                        </Checkbox>
                      )}
                    </Col>
                  </Row>

                  {/*3，送积分*/}
                  <Row gutter={{ ...rowGutterPxLayout }}>
                    <Col {...colSpanLayout}>
                      {getFieldDecorator(`preferential.isGiftScore-${index}`, {
                        initialValue: item.isGiftScore,
                      })(
                        <Checkbox
                          checked={item.isGiftScore}
                          disabled={type === 'view'}
                          style={{ display: 'block', marginTop: 20, marginLeft: 115 }}
                          onChange={e => {
                            item.isGiftScore = e.target.checked;
                            item.score = 0;
                            this.props.form.setFieldsValue({
                              preferential: {
                                [`score-${index}`]: undefined,
                              },
                            });
                          }}
                        />
                      )}
                      <FormItem style={{ marginTop: -30, marginLeft: 140 }} {...formItemLayout}>
                        送
                        {type === 'view'
                          ? item.score
                          : getFieldDecorator(`preferential.score-${index}`, {
                              initialValue: item.score,
                              rules: [rulesReg('busInt')],
                            })(
                              <Input
                                style={{ width: 150, marginLeft: 5, marginRight: 5 }}
                                disabled={!item.isGiftScore}
                                type="text"
                                autocomplete="off"
                                placeholder="积分"
                                onChange={event => {
                                  item.score = event.target.value;
                                }}
                              />
                            )}
                        积分
                      </FormItem>
                    </Col>
                  </Row>

                  {/*送优惠券*/}
                  <Row gutter={{ ...rowGutterPxLayout }}>
                    <Col {...colSpanLayout}>
                      <FormItem
                        style={{ marginLeft: 115 }}
                        {...formItemLayout}
                        extra={
                          item.existCoupon ? (
                            // eslint-disable-next-line react/no-array-index-key
                            <div key={index}>
                              {type !== 'view' && (
                                <a
                                  onClick={() => {
                                    this.openSelectCoupon(index);
                                  }}
                                >
                                  选择优惠券
                                </a>
                              )}
                              {item.preferentialObjsCoupon.length > 0 && (
                                <Table
                                  rowKey="id"
                                  style={{ minWidth: '710px' }}
                                  columns={this.getCouponColumns(index)}
                                  dataSource={item.preferentialObjsCoupon}
                                />
                              )}
                            </div>
                          ) : (
                            '无'
                          )
                        }
                      >
                        {type === 'view'
                          ? '送优惠券'
                          : getFieldDecorator(`preferential.existCoupon-${index}`, {
                              initialValue: item.existCoupon,
                              rules: [],
                            })(
                              <Checkbox
                                // style={{marginLeft: 115, marginTop: 20}}
                                checked={item.existCoupon}
                                onChange={e => {
                                  item.existCoupon = e.target.checked;
                                  item.preferentialObjsCoupon = [];
                                }}
                              >
                                送优惠券
                              </Checkbox>
                            )}
                      </FormItem>
                    </Col>
                  </Row>

                  {/*送赠品*/}
                  <Row gutter={{ ...rowGutterPxLayout }}>
                    <Col {...colSpanLayout}>
                      <FormItem
                        style={{ marginLeft: 115 }}
                        {...formItemLayout}
                        extra={
                          item.existGift ? (
                            // eslint-disable-next-line react/no-array-index-key
                            <div key={index}>
                              {type !== 'view' && (
                                <a
                                  onClick={() => {
                                    this.openSelectGift(index);
                                  }}
                                >
                                  选择赠品
                                </a>
                              )}
                              {item.preferentialObjsGift.length > 0 && (
                                <Table
                                  rowKey="id"
                                  style={{ minWidth: '710px' }}
                                  columns={this.getGiftColumns(index)}
                                  dataSource={item.preferentialObjsGift}
                                />
                              )}
                            </div>
                          ) : (
                            '无'
                          )
                        }
                      >
                        {type === 'view'
                          ? '送赠品'
                          : getFieldDecorator(`preferential.existGift-${index}`, {
                              initialValue: item.existGift,
                              rules: [],
                            })(
                              <Checkbox
                                checked={item.existGift}
                                onChange={e => {
                                  item.existGift = e.target.checked;
                                  item.preferentialObjsGift = [];
                                }}
                              >
                                送赠品
                              </Checkbox>
                            )}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              ))
          )}
          {type !== 'view' && this.state.preferentialList.length <= 4 && model.circleType === 0 && (
            <Button onClick={this.addRow} style={{ marginTop: '20px' }}>
              添加一行
            </Button>
          )}
        </Card>

        {/*选择商品modal*/}
        <Modal
          width={700}
          height={500}
          visible={this.state.isShowSelectProduct}
          title="选择商品"
          onCancel={() => {
            this.setState({
              isShowSelectProduct: false,
            });
          }}
          onOk={this.okSelectProduct}
          destroyOnClose
        >
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <Input
                type="text"
                autocomplete="off"
                placeholder="商品名称"
                onChange={e => {
                  this.setState({
                    likeProductName: e.target.value,
                  });
                }}
                onPressEnter={this.requestList}
              />
            </Col>
            <Col {...colSpanLayout}>
              <Button type="primary" icon="search" onClick={this.requestList}>
                <FormattedMessage id="ours.curd.list.base-form.search" defaultMessage="查询" />
              </Button>
            </Col>
          </Row>
          <ETable
            onSelectRow={uiUtils.onSelectRow.bind(this)}
            primaryKey="id"
            selectedRows={this.state.selectedRows}
            selectedIds={this.state.selectedIds}
            selectedIndexs={this.state.selectedIndexs}
            columns={selectProductColumns}
            dataSource={this.state.list}
            pagination={this.state.pagination}
            loading={this.state.loading}
            scroll={{ x: 600 }}
          />
        </Modal>

        {/*选择优惠券*/}
        <Modal
          width={700}
          height={500}
          visible={this.state.isShowSelectCoupon}
          title="选择优惠券"
          onCancel={() => {
            this.setState({
              isShowSelectCoupon: false,
            });
          }}
          onOk={this.okSelectCoupon}
          destroyOnClose
        >
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <Input
                type="text"
                autocomplete="off"
                placeholder="优惠券名称"
                onChange={e => {
                  this.setState({
                    likeCouponName: e.target.value,
                  });
                }}
                onPressEnter={this.requestCouponList}
              />
            </Col>
            <Col {...colSpanLayout}>
              <Button type="primary" icon="search" onClick={this.requestCouponList}>
                <FormattedMessage id="ours.curd.list.base-form.search" defaultMessage="查询" />
              </Button>
            </Col>
          </Row>
          <ETable
            onSelectRow={uiUtils.onSelectRow.bind(this)}
            primaryKey="id"
            selectedRows={this.state.selectedRows}
            selectedIds={this.state.selectedIds}
            selectedIndexs={this.state.selectedIndexs}
            columns={preferentialObjsCouponColumns}
            dataSource={this.state.couponList}
            pagination={this.state.pagination}
            loading={this.state.loading}
            scroll={{ x: 600 }}
          />
        </Modal>

        {/*选择赠品*/}
        <Modal
          width={700}
          height={500}
          visible={this.state.isShowSelectGift}
          title="选择赠品"
          onCancel={() => {
            this.setState({
              isShowSelectGift: false,
            });
          }}
          onOk={this.okSelectGift}
          destroyOnClose
        >
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <Input
                type="text"
                autocomplete="off"
                placeholder="赠品名称"
                onChange={e => {
                  this.setState({
                    likeGiftName: e.target.value,
                  });
                }}
                onPressEnter={this.requestGiftList}
              />
            </Col>
            <Col {...colSpanLayout}>
              <Button type="primary" icon="search" onClick={this.requestGiftList}>
                <FormattedMessage id="ours.curd.list.base-form.search" defaultMessage="查询" />
              </Button>
            </Col>
          </Row>
          <ETable
            onSelectRow={uiUtils.onSelectRow.bind(this)}
            primaryKey="id"
            selectedRows={this.state.selectedRows}
            selectedIds={this.state.selectedIds}
            selectedIndexs={this.state.selectedIndexs}
            columns={preferentialObjsGiftColumns}
            dataSource={this.state.giftList}
            pagination={this.state.pagination}
            loading={this.state.loading}
            scroll={{ x: 600 }}
          />
        </Modal>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
